package bmoofxbridge;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.ofx.types.x2003.x04.OFXDocument;

import org.mortbay.http.HttpResponse;
import org.w3c.dom.Document;

public class ReportServlet extends HttpServlet {
	public static DataProcessor processor;
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
		response.setContentType("application/xml");
		response.setCharacterEncoding("utf-8");
		ServletOutputStream os = response.getOutputStream();
		StringWriter strWrt = new StringWriter();
		BufferedReader reader = request.getReader();
		copyReader(reader, strWrt);

		String requestTxt = strWrt.toString();
		System.out.println("Request:"+requestTxt);
		
		
		//ServletInputStream is = request.getInputStream();
		StringReader sReader = new StringReader(requestTxt);
		
		Document domDoc = processor.parseRequestReader(sReader);
		Document report = processor.getReport(domDoc);
		processor.saveReport(report, os);
		System.out.println("Done!");
		//FileInputStream is = new FileInputStream("D:\\Work\\Development\\Projects\\BMOFXBridge\\src\\xml\\test2.ofx");
		//copyStream(is, os);
		
		//doGet(arg0, response);
		}
		catch (Exception e) {
			throw new ServletException(e);
		}
	}
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
			ServletOutputStream os = response.getOutputStream();

			System.out.println("Please, Login!");
			processor.loginToBMO();
			System.out.println("Extracting Data");
			processor.extractData();
			System.out.println("Preparing Report");
			Document report = processor.getReport(null);
			System.out.println("Saving Report");
			processor.saveReport(report, os);
			System.out.println("Done!");
		}
		catch (Exception e) {
			throw new ServletException(e);
		}
	}
	
	public int copyStream(InputStream is, OutputStream os){
		try{
			int byte_;
		     while ((byte_ = is.read ()) != -1)
		       os.write (byte_);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return 1;
	}
	
	public int copyReader(Reader reader, Writer writer){
		try {
		int char_;
			while ((char_ = reader.read ()) != -1)
				writer.write (char_);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}
		
}
